<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Mihail Merkov
 * Date: 13-8-11
 * Time: 20:27
 * To change this template use File | Settings | File Templates.
 */

namespace TennisTournament\Persistent;
use Doctrine\ORM\EntityManager;

class GenericDaoDoctrine implements GenericDao {

    /** @var string */
    private $entityPath;

    /** @var EntityManager */
    protected $entityManager;

    public function __construct(EntityManager $entityManager, $entityPath) {
        $this->entityManager = $entityManager;
        $this->entityPath = $entityPath;
    }

    /**
     * Get an entity by its {@link $id}
     * @param $id integer
     * @return an entity if have with such id or null otherwise
     * @throws \Exception
     */
    public function get($id){
        return $this->entityManager->find($this->entityPath, $id);
    }

    /**
     * Get all entities from specific type
     * @return Array from all entities from specific type
     * @throws \Exception
     */
    public function fetchAll() {
        return $this->entityManager->getRepository($this->entityPath)->findAll();
    }

    /**
     * Save an specific entity;
     * @param entity
     * @return void
     * @throws \Exception
     */
    public function save($entity) {
        $this->entityManager->persist($entity);
        $this->entityManager->flush();
    }

    /**
     * Delete an specific entity;
     * @param entity
     * @return void
     * @throws \Exception
     */
    public function delete($entity) {
        $this->entityManager->remove($entity);
        $this->entityManager->flush();
    }

    /**
     * Starts a transaction by suspending auto-commit mode.
     * @return void
     */
    public function startTransaction(){
        $this->entityManager->getConnection()->beginTransaction();
    }

    /**
     * Commits a transaction on the underlying database connection.
     */
    public function commitTransaction() {
        $this->entityManager->getConnection()->commit();
    }

    /**
     * Cancel any database changes done during the current transaction.
     */
    public function rollbackTransaction() {
        $this->entityManager->getConnection()->rollBack();
    }
}